package com.geeklan.smart.ui.device;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.base.utils.MLog;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.RequestDevice;
import com.geeklan.smart.data.remote.rtc.RtcEngineManager;
import com.geeklan.smart.data.repository.device.DeviceRepository;
import com.geeklan.smart.permission.PermissionManager;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModel;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModelFactory;
import com.geeklan.smart.utils.FileUtils;
import com.geeklan.smart.utils.SharedPreferencesUtil;

import io.agora.rtc2.ChannelMediaOptions;
import io.agora.rtc2.Constants;
import io.agora.rtc2.IRtcEngineEventHandler;
import io.agora.rtc2.RtcEngine;
import io.agora.rtc2.RtcEngineConfig;
import io.agora.rtc2.video.VideoCanvas;

import com.geeklan.smart.databinding.ActivityVideoCallBinding;
import com.geeklan.smart.utils.TimeUtils;
import com.geeklan.smart.widget.VideoRightFeedingPopupWindow;

public class VideoCallActivity extends BaseActivity<ActivityVideoCallBinding>{
    private DeviceViewModel deviceViewModel;
    private String token;
    private String token1;
    private int userId = 0;
    private RtcEngineManager rtcEngineManager;
    private RtcEngineManager rtcEngineManager1;
    private String deviceId;
    private String path = FileUtils.getExternalFilesDir();
    private int typePosition;

    @Override
    protected ActivityVideoCallBinding initBinding() {
        return ActivityVideoCallBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        userId = SharedPreferencesUtil.getInt("userId", 0);
        deviceId = getIntent().getStringExtra("deviceId");
        deviceViewModel = new ViewModelProvider(this, new DeviceViewModelFactory(new DeviceRepository())).get(DeviceViewModel.class);
        tokenLiveData();
        feedLiveData();
    }

    private void tokenLiveData() {
        deviceViewModel.getDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            token = apiResponse.getData().getToken();
            initRtc(0);
        });

        deviceViewModel.getDeviceLiveData1().observe(this, apiResponse -> {
            dismiss();
            token1 = apiResponse.getData().getToken();
            initRtc(1);
        });
        deviceViewModel.getErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }

    private void feedLiveData() {
        deviceViewModel.getFeedPlanDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            deviceViewModel.controlOpenFeed(deviceId, typePosition == 0 ? 1 : 0);
        });

        deviceViewModel.getFeedPlanErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });


        deviceViewModel.getFeedDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            Toast.makeText(this, R.string.feed_success, Toast.LENGTH_SHORT).show();
        });

        deviceViewModel.getFeedErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getWindow().getDecorView().setSystemUiVisibility(
//                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
//                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                        | View.SYSTEM_UI_FLAG_FULLSCREEN
//                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        if (PermissionManager.checkPermissions(this)) {
            deviceViewModel.getDeviceAccessToken(deviceId, userId);
            new Handler().postDelayed(() -> {
                deviceViewModel.getDeviceAccessToken1(deviceId + "_1", userId * 10000);
            }, 200);
        } else {
            ActivityCompat.requestPermissions(this, PermissionManager.getRequiredPermissions(), PERMISSION_REQ_ID);
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (rtcEngineManager != null && rtcEngineManager1 != null && (!TextUtils.isEmpty(rtcEngineManager.getAliImagePath()) || !TextUtils.isEmpty(rtcEngineManager.getAliImagePath()))) {
                deviceViewModel.uploadDeviceVideoImg(deviceId, rtcEngineManager.getAliImagePath(), rtcEngineManager1.getAliImagePath());
            }else {
                handler.sendMessageDelayed(msg,2000);
            }
            return false;
        }
    });

    @Override
    protected void onPause() {
        if (rtcEngineManager != null) {
            rtcEngineManager.closeVideo();
        }
        if (rtcEngineManager1 != null) {
            rtcEngineManager1.closeVideo();
        }
        super.onPause();
    }

    private void initRtc(int type) {
        if (type == 0) {
            rtcEngineManager = new RtcEngineManager(this, mBinding.remoteVideoViewContainer, token, deviceId, userId);
            rtcEngineManager.setRtcEngineEventListener(new RtcEngineManager.RtcEngineEventListener() {
                @Override
                public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
                    mBinding.ivPhoto.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onUserOffline(int uid, int reason) {
                    mBinding.ivPhoto.setVisibility(View.VISIBLE);
                    mBinding.remoteVideoViewContainer.setVisibility(View.INVISIBLE);
                }

                @Override
                public void upLoadSuccess(String url) {
                    handler.sendEmptyMessageDelayed(0, 5000);
                }
            });
            rtcEngineManager.joinChannel();
        } else {
            rtcEngineManager1 = new RtcEngineManager(this, mBinding.remoteVideoViewContainer1, token1, deviceId + "_1", userId * 10000);
            rtcEngineManager1.setRtcEngineEventListener(new RtcEngineManager.RtcEngineEventListener() {
                @Override
                public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
                    mBinding.ivPhoto1.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onUserOffline(int uid, int reason) {
                    mBinding.ivPhoto1.setVisibility(View.VISIBLE);
                    mBinding.remoteVideoViewContainer1.setVisibility(View.INVISIBLE);
                }

                @Override
                public void upLoadSuccess(String url) {
                    handler.sendEmptyMessageDelayed(0, 5000);
                }
            });
            rtcEngineManager1.joinChannel();
        }
    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(onClickListener);
        mBinding.ivScreenshot.setOnClickListener(onClickListener);
        mBinding.ivAudio.setOnClickListener(onClickListener);
        mBinding.ivSoundRecording.setOnClickListener(onClickListener);
        mBinding.ivFeed.setOnClickListener(onClickListener);

        mBinding.remoteVideoViewContainer1.setOnClickListener(v -> {
            switchLines();
        });
    }

    public void switchLines() {
        ViewGroup parent = (ViewGroup) mBinding.remoteVideoViewContainer1.getParent();

        if (!(parent instanceof ConstraintLayout)) return;
        ConstraintLayout.LayoutParams paramsA = (ConstraintLayout.LayoutParams) mBinding.remoteVideoViewContainer.getLayoutParams();
        ConstraintLayout.LayoutParams paramsB = (ConstraintLayout.LayoutParams) mBinding.remoteVideoViewContainer1.getLayoutParams();

        ConstraintLayout.LayoutParams temp = new ConstraintLayout.LayoutParams(paramsA);
        mBinding.remoteVideoViewContainer.setLayoutParams(paramsB);
        mBinding.remoteVideoViewContainer1.setLayoutParams(temp);

        int indexA = parent.indexOfChild(mBinding.remoteVideoViewContainer);
        int indexB = parent.indexOfChild(mBinding.remoteVideoViewContainer1);

        parent.removeView(mBinding.remoteVideoViewContainer);
        parent.removeView(mBinding.remoteVideoViewContainer1);

        if (indexA < indexB) {
            parent.addView(mBinding.remoteVideoViewContainer1, indexA);
            parent.addView(mBinding.remoteVideoViewContainer, indexB);
        } else {
            parent.addView(mBinding.remoteVideoViewContainer, indexB);
            parent.addView(mBinding.remoteVideoViewContainer1, indexA);
        }
//        if (rtcEngineManager.getRemoteVideoViewContainer().getId() == mBinding.remoteVideoViewContainer.getId()) {
//            mBinding.remoteVideoViewContainer.removeAllViews();
//            mBinding.remoteVideoViewContainer1.removeAllViews();
//            rtcEngineManager1.checkVideo(mBinding.remoteVideoViewContainer);
//            new Handler().postDelayed(() -> {
//                rtcEngineManager.checkVideo(mBinding.remoteVideoViewContainer1);
//            }, 200);
//        } else {
//            mBinding.remoteVideoViewContainer.removeAllViews();
//            mBinding.remoteVideoViewContainer1.removeAllViews();
//            rtcEngineManager.checkVideo(mBinding.remoteVideoViewContainer);
//            new Handler().postDelayed(() -> {
//                rtcEngineManager1.checkVideo(mBinding.remoteVideoViewContainer1);
//            }, 200);
//        }
    }

    private boolean isAudio = false;
    private boolean isSoundRecording = false;

    View.OnClickListener onClickListener = v -> {
        int id = v.getId();
        if (id == mBinding.ivBack.getId()) {
            rtcEngineManager.closeVideo();
            rtcEngineManager1.closeVideo();
            finish();
        } else if (id == mBinding.ivAudio.getId()) {
            if (isAudio) {
                isAudio = false;
                rtcEngineManager.setEnableSpeakerphone(isAudio);
                mBinding.ivAudio.setImageDrawable(ActivityCompat.getDrawable(this, R.drawable.ic_switch_audio_close));
            } else {
                isAudio = true;
                rtcEngineManager.setEnableSpeakerphone(isAudio);
                mBinding.ivAudio.setImageDrawable(ActivityCompat.getDrawable(this, R.drawable.ic_switch_audio_open));
            }
        } else if (id == mBinding.ivSoundRecording.getId()) {
            if (isSoundRecording) {
                isSoundRecording = false;
                rtcEngineManager.setPublishMicrophoneTrack(isSoundRecording);
                mBinding.ivSoundRecording.setImageDrawable(ActivityCompat.getDrawable(this, R.drawable.ic_switch_sound_recording_close));
            } else {
                isSoundRecording = true;
                rtcEngineManager.setPublishMicrophoneTrack(isSoundRecording);
                mBinding.ivSoundRecording.setImageDrawable(ActivityCompat.getDrawable(this, R.drawable.ic_switch_sound_recording_open));
            }
        } else if (id == mBinding.ivFeed.getId()) {
            VideoRightFeedingPopupWindow popupWindow = new VideoRightFeedingPopupWindow(this);
            popupWindow.setConfirmButtonClickListener((typePosition, numberPosition) -> {
                this.typePosition = typePosition;
                deviceViewModel.resetFeedNum(deviceId, typePosition == 0 ? numberPosition : 0, typePosition == 1 ? numberPosition : 0);
                popupWindow.dismiss();
            });
            popupWindow.showPopup(mBinding.main); // 绑定到根布局
        } else if (id == mBinding.ivScreenshot.getId()) {
            if (!PermissionManager.checkStoragePermissions(this)) {
                requestPermissions(PermissionManager.getStoragePermissions(), 1);
            } else {
                rtcEngineManager.takeSnapshot(userId, path, true);
            }
        }
    };

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    @Override
    public void onPermissionsResultSuccess() {

    }

    @Override
    public void onPermissionsResultFail() {

    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context, String deviceId) {
        Intent intent = new Intent(context, VideoCallActivity.class);
        intent.putExtra("deviceId", deviceId);
        context.startActivity(intent);
    }
}